<template>
  <div
    class="app-conainer"
    style="display: flex; flex-direction: column; height: 100vh"
  >
    <Header></Header>
    <div class="container-wapper flex">
      <div class="wapper-nav">
        <div
          :class="
            activeNav == 1 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(1)"
        >
          <img
            v-if="activeNav == 1"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img v-if="activeNav == 1" src="~@/assets/home-active.png" alt="" />
          <img v-else src="~@/assets/home.png" alt="" />
          <div class="nav-title">首页</div>
        </div>
        <div
          :class="
            activeNav == 2 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(2)"
        >
          <img
            v-if="activeNav == 2"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img v-if="activeNav == 2" src="~@/assets/vip-active.png" alt="" />
          <img v-else src="~@/assets/vip.png" alt="" />
          <div class="nav-title">开通会员</div>
        </div>
        <div
          :class="
            activeNav == 3 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(3)"
        >
          <img
            v-if="activeNav == 3"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img v-if="activeNav == 3" src="~@/assets/car-active.png" alt="" />
          <img v-else src="~@/assets/car.png" alt="" />
          <div class="nav-title">购买记录</div>
        </div>
        <div
          :class="
            activeNav == 4 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(4)"
        >
          <img
            v-if="activeNav == 4"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img
            v-if="activeNav == 4"
            src="~@/assets/invitation-active.png"
            alt=""
          />
          <img v-else src="~@/assets/invitation.png" alt="" />
          <div class="nav-title">邀请返利</div>
        </div>
        <div
          :class="
            activeNav == 5 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(5)"
        >
          <img
            v-if="activeNav == 5"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img
            v-if="activeNav == 5"
            src="~@/assets/customer-active.png"
            alt=""
          />
          <img v-else src="~@/assets/customer.png" alt="" />
          <div class="nav-title">联系客服</div>
        </div>
        <div
          :class="
            activeNav == 6 ? 'choose-navitem nav-item flex' : 'nav-item flex'
          "
          @click="changeNav(6)"
        >
          <img
            v-if="activeNav == 6"
            class="border-left"
            src="~@/assets/border-left.png"
            alt=""
          />
          <img
            v-if="activeNav == 6"
            src="~@/assets/link-active.png"
            alt=""
          />
          <img v-else src="~@/assets/link.png" alt="" />
          <div class="nav-title">快捷导航</div>
        </div>
      </div>
      <div class="wapper-content">
        <Concat ref="concat" v-if="activeNav == 1"></Concat>
        <OpenVip v-if="activeNav == 2" @changeNav="changeNav"></OpenVip>
        <BuyLog v-if="activeNav == 3"></BuyLog>
        <LnviteRebate v-if="activeNav == 4"></LnviteRebate>
        <ConcatService v-if="activeNav == 5"></ConcatService>
        <Link v-if="activeNav == 6"></Link>
      </div>
    </div>
    <div class="container-bottom flex">
      <div class="bottom1 flex">
        <div class="bottom-label">连接状态：</div>
        <div
          class="bottom-value"
          :style="$store.state.Counter.isStart == true ? '' : 'color:#FE2627'"
        >
          {{ $store.state.Counter.isStart == true ? "已连接" : "未连接" }}
        </div>
      </div>
      <div class="bottom2 flex">
        <div class="bottom-label">监听端口：</div>
        <div class="bottom-value">7896</div>
      </div>
      <div class="bottom3 flex">
        <div class="bottom-label">剩余时长：</div>
        <div class="bottom-value" :style="showTime == '0秒' || showTime == '' ? 'color:#FE2627' : ''">
          {{ showTime == "0秒" || showTime == '' ? "已过期" : showTime }}
        </div>
      </div>
      <div class="bottom4 flex">
        <div class="bottom-label">剩余流量：</div>
        <div class="bottom-value" :style="userInfo.unused_traffic == '0B' ? 'color:#FE2627' : ''">
          {{ userInfo.unused_traffic }}
        </div>
        <img class="bottom-refresh" src="~@/assets/refresh.png" @click="refreshTraffic()"/>
      </div>
    </div>
  </div>
</template>

<script>
import {getUserInfo, getConfigNode, setConfigNodeCoreAPI, onlineTicket} from "../utils/api";
import {getConfigPath, getCoreExePath, getUserHomeConfig, writeConfigToPath} from '../utils/fileUtils'
const fs = require("fs");
const { exec,spawn } = require('child_process');
const { remote } = require('electron')
import Header from "./Component/Header.vue";
import Concat from "./Component/Concat.vue";
import OpenVip from "./Component/OpenVip.vue";
import ConcatService from "./Component/ConcatService.vue";
import LnviteRebate from "./Component/LnviteRebate.vue";
import BuyLog from "./Component/BuyLog.vue";
import Link from "./Component/Link.vue";
import bus from '../utils/bus'
export default {
  name: "home-page",
  components: {
    Concat,
    OpenVip,
    ConcatService,
    LnviteRebate,
    Link,
    BuyLog,
    Header
  },
  data() {
    return {
      activeNav: 1,
      timers: "",
      vipTime: 365 * 24 * 60 * 60 * 1000,
      showTime: "",
      userInfo:{},
      isExpire: true,
    };
  },
  methods: {
    changeNav(index) {
      this.activeNav = index;
      if(index == 1){
        this.$localStore.set("isFirst",false)
      }
    },
    forMatTime(timers) {
      let second_time = parseInt(timers / 1000);
      var time = parseInt(second_time) + "秒";
      if (parseInt(second_time) > 60) {
        var second = parseInt(second_time) % 60;
        var min = parseInt(second_time / 60);
        time = min + "分" + second + "秒";
        if (min > 60) {
          min = parseInt(second_time / 60) % 60;
          var hour = parseInt(parseInt(second_time / 60) / 60);
          time = hour + "小时" + min + "分" + second + "秒";
          if (hour > 24) {
            hour = parseInt(parseInt(second_time / 60) / 60) % 24;
            var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
            time = day + "天" + hour + "小时" + min + "分" + second + "秒";
          }
        }
      }
      return time;
    },
    handleUserInfo(isRefresh){
      let userId = this.$localStore.get("userInfo").user_id;
      getUserInfo(userId).then(res => {
        this.loading = false
        if(res.data.ret == 1){
          this.userInfo = res.data.data.user
          this.$localStore.set("userInfo",res.data.data.user)
          const class_expire = this.userInfo.class_expire;
          this.isExpire = new Date().getTime() > new Date(class_expire).getTime();
          if(!this.isExpire){
            this.updateConfigNode(isRefresh)
            this.handleTimer()
          }else{
            this.$message.info("当前无可用节点，请购买会员套餐")
          }
          bus.$emit('updateVip')
          this.$localStore.set("isExpire",this.isExpire)
          this.getIframeUrl()
        }else{
          this.$message.error(res.data.msg)
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    refreshTraffic(){
      this.handleUserInfo(false)
    },
    updateConfigNode(isRefresh) {
      const configUrl = getConfigPath();
      if (this.userInfo != null &&  this.userInfo != "") {
        getConfigNode(this.userInfo.node_url).then((res) => {
          // 更新节点信息，如果节点信息未返回、则提示购买会员
          if(res.response && res.response.status == 400){
            this.$message.info("当前无可用节点，请购买会员套餐")
          }else{
            let that = this;
            if(!isRefresh){
              return false;
            }else{
              fs.writeFile(configUrl, res.data, function (err) {
                if(err){
                  that.$message.error("更新节点失败")
                }else{
                  that.$message.success("节点更新完成")
                  that.startCoreProcess()
                  if(that.$refs['concat']){
                    that.$refs['concat'].getNodeList(true)
                  }
                }
              });
            }
          }
        })
      }
    },
    //启动核心程序
    startCoreProcess(){
      const configUrl = getCoreExePath();
      spawn(configUrl);
      this.setUserHomeConfig()
    },
    //设置用户根目录文件配置
    setUserHomeConfig(){
      const fileName = "config.yaml"
      const remotePort = this.$localStore.get("remotePort");
      let text = getUserHomeConfig(remotePort)
      writeConfigToPath(text,fileName)
      this.settingConfigNode()
    },
    //设置配置文件节点
    settingConfigNode(){
      const configUrl =getConfigPath();
      const data = {path: configUrl}
      setConfigNodeCoreAPI(data).then(res=>{
        if(res){}else{}
      })
    },
    // 获取在线连接
    getIframeUrl(){
      this.loading = true
      onlineTicket().then(res => {
        if(res.data && res.data.ret == 1){
          this.onlineUrl=res.data.data.online
        }else{
          this.$message.error(res.data.msg)
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    handleTimer(){
      this.timers = setInterval(() => {
        this.vipTime = new Date(this.userInfo.class_expire).getTime() - new Date().getTime()
        if(this.vipTime<=0){
          clearInterval(this.timers);
          this.timers = "";
          return
        }
        this.showTime = this.forMatTime(this.vipTime);
        this.vipTime -= 1000;
      }, 1000);
    }
  },
  created() {
    this.timers = setInterval(() => {
      this.vipTime = new Date(this.userInfo.class_expire).getTime() - new Date().getTime()
      if(this.vipTime<=0){
        clearInterval(this.timers);
        this.timers = "";
        return
      }
      this.showTime = this.forMatTime(this.vipTime);
      this.vipTime -= 1000;
    }, 1000);
      //连接状态
      this.$electron.ipcRenderer.send("concat-status", this.$localStore.get("isStart"));
      //打开在线客服
      this.$electron.ipcRenderer.on("show-online", ()=>{
        this.$electron.ipcRenderer.send("open-online",this.$localStore.get("onlineUrl"));
      });
    //检查更新
      this.$electron.ipcRenderer.on("is-update", ()=>{
        this.$message.success('检查更新中------')
      });
      //断开连接
      this.$electron.ipcRenderer.on("disconnect", ()=>{
        this.$store.commit('CHANGE_ISSART',false)
        this.$localStore.set("isStart",false)
        this.$electron.ipcRenderer.send("dis-connect");
        this.$refs['concat'].changeStatus(false)
      });
  },
  mounted(){
    remote.getCurrentWindow().setSize(1000, 680)
    this.handleUserInfo(true)
    this.$localStore.set("isFirst",true)
    bus.$on('getUser',(e)=>{
      this.handleUserInfo(true)
    })
  },
  destroyed() {
    clearInterval(this.timers);
    this.timers = "";
  }
};
</script>

<style>
@import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro");
.app-container {
  width: 100%;
}
.container-wapper {
  flex: 1;
}

.wapper-nav {
  width: 200px;
  height: 100%;
  background: #24262f;
}
.nav-item {
  width: 200px;
  height: 66px;
  background: #303440;
  margin-bottom: 2px;
  cursor: pointer;
  position: relative;
}

.choose-navitem {
  color: #09d0ce;
  /* border-left: 2px solid #09d0ce; */
}
.nav-item .nav-title {
  width: 64px;
  text-align: center;
}
.nav-item img {
  width: 24px;
  height: 24px;
  margin-right: 13px;
}
.nav-item .border-left {
  position: absolute;
  left: 0;
  top: 0;
  height: 66px;
  width: 6px;
}
.wapper-content {
  flex: 1;
  height: 100%;
}

.container-bottom {
  width: 100%;
  height: 46px;
}
.container-bottom > div {
  width: 25%;
  height: 100%;
  background: #444752;
  cursor: pointer;
}
.container-bottom .bottom2 {
  background: #3d414c;
}
.container-bottom .bottom3 {
  background: #393c46;
}
.container-bottom .bottom4 {
  background: #313540;
}
.bottom-refresh {
  margin-left: 13px;
  width: 20px;
  height: 18px;
}
.bottom-value {
  color: #09d0ce;
}
</style>